package org.cweili.vehicle.servlet

import groovy.util.logging.Commons

import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import org.apache.commons.lang.StringUtils
import org.cweili.vehicle.entity.Customer
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.Utils

import com.alibaba.fastjson.JSONObject

/**
 * 权限过滤
 *
 * @author Cweili
 * @version 2013年7月28日 下午6:51:54
 *
 */
@Commons
class AuthenticationFilter implements Filter {

	@Override
	void init(FilterConfig config) throws ServletException {
	}

	@Override
	void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	throws IOException, ServletException {
		def httpRequest = (HttpServletRequest) request

		final def requestUri = StringUtils.substringAfter(httpRequest.getRequestURI(),
				"${httpRequest.getContextPath()}/")
		if (Utils.startsWithIgnoreCase(requestUri, Const.ALLOW_NOT_LOGIN)) {
			chain.doFilter(request, response)
			return
		}

		def httpResponse = (HttpServletResponse) response
		def session = httpRequest.getSession(false)

		// 从 Session 中取登录用户信息，如果无法取得，则尝试从 Cookie 中获取
		if (!session || !session.getAttribute(Const.SESSION_CUSTOMER)) {
			if (httpRequest.getCookies()) {
				for (cookie in httpRequest.getCookies()) {
					if (Const.COOKIE_CUSTOMER.equalsIgnoreCase(cookie.getName())) {
						try {
							def json = URLDecoder.decode(cookie.getValue(), Const.CHARSET)
							log.info("Cookie Login: ${cookie.getName()} ${json}")
							def customer = JSONObject.parseObject(json, Customer.class)
							session = httpRequest.getSession()
							session.setAttribute(Const.SESSION_CUSTOMER, customer)
						} catch (Exception e) {
							log.error(e, e)
						}
						break
					}
				}
			}
		}

		if (!session || !session.getAttribute(Const.SESSION_CUSTOMER)) {
			forwardLogin(httpRequest, httpResponse) // 无法取得登录用户信息，返回登录页面
			return
		} else {
			Customer customer = (Customer) session.getAttribute(Const.SESSION_CUSTOMER)
			if (Customer.CLASS_ADMIN > customer.getClassification()
			&& Utils.startsWithIgnoreCase(requestUri, Const.ADMIN_PREFIX)) { // 管理员权限判断
				session.removeAttribute(Const.SESSION_CUSTOMER)
				forwardLogin(httpRequest, httpResponse)
				return
			} else if (Customer.CLASS_DRIVER > customer.getClassification()
			&& Utils.startsWithIgnoreCase(requestUri, Const.DRIVER_PREFIX)) { // 司机权限判断
				session.removeAttribute(Const.SESSION_CUSTOMER)
				forwardLogin(httpRequest, httpResponse)
				return
			}
		}

		chain.doFilter(httpRequest, httpResponse)
	}

	@Override
	void destroy() {

	}

	private forwardLogin(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
		response.sendRedirect("${request.getContextPath()}/login.html")
	}

}
